/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import { Form, Input, Checkbox, Select, TreeSelect, Button, message, Upload, Icon } from 'antd';
import {connect} from 'dva';
import moment from 'moment';

import request from '@/utils/request';
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import config from '@/config/config'

const { TreeNode } = TreeSelect;
const FormItem = Form.Item;
const Option = Select.Option;
@connect(({ webMail, loading,global }) => ({
  webMail,
  global,
  loading: loading.models.webMail,
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      all_roles:[],
      all_receiver:[],
      editorState: BraftEditor.createEditorState(''), // 设置编辑器初始内容
      indeterminate: false,
      checkAll: false,
      checkedList:[],
      fileList:[]
    };
  }
  componentDidMount() {
    const that=this;
    const mailHistory=localStorage.getItem('mailHistory');
    console.log('mailHistory',mailHistory)
    if(mailHistory){
      this.setState({
        editorState:BraftEditor.createEditorState(mailHistory)
      })
    }
    this.timer=setInterval(function() {
      console.log('保存草稿')
      localStorage.setItem('mailHistory',that.state.editorState.toHTML())
    },10000)

    request(`/all_departments`, {
      method: 'GET',
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        that.setState({
          all_roles:response.data.data
        })
      }
    })

  }
  componentWillUnmount() {
    if(this.timer){
      clearInterval(this.timer)
    }
  }

  changeRoles=(value)=>{
    console.log('value',value)
    const that=this;
    request(`/all_staffs`, {
      method: 'GET',
      params:{
        department_ids:value
      }
    }).then((response)=> {
      console.log('all_receiver', response)
      if(response.status===200){
        let all_receiver=[];
        let checkedList=[];
        for(let i=0;i<response.data.data.length;i++){
          all_receiver.push({ label: response.data.data[i].name, value: response.data.data[i].id},)
          if(that.state.checkedList.indexOf(response.data.data[i].id)>=0){
            checkedList.push(response.data.data[i].id)
          }

        }
        that.setState({
          all_receiver:all_receiver,
          checkedList:checkedList
        },function() {
          that.setState({
            indeterminate: !!checkedList.length && checkedList.length < that.state.all_receiver.length,
            checkAll: checkedList.length === that.state.all_receiver.length,
          })
        })
      }
    })
  }
  handleChange = (editorState) => {
    this.setState({
      editorState: editorState,
      // outputHTML: editorState.toHTML()
    })
  }
  renderTreeNodes=(data)=>{
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode  value={`${item.id}`} title={item.name} key={item.id} >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return  <TreeNode value={item.id}  title={item.name} key={item.id} />
    });
  }
  onChange = checkedList => {
    console.log('checkedList',checkedList)
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < this.state.all_receiver.length,
      checkAll: checkedList.length === this.state.all_receiver.length,
    });
  };

  onCheckAllChange = e => {
    let checkedList=[];
    console.log('this.state.all_receiver',this.state.all_receiver)
    for(let i=0;i<this.state.all_receiver.length;i++){
      checkedList.push(this.state.all_receiver[i].value)
    }
    this.setState({
      checkedList: e.target.checked ? checkedList : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 2},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 22},
      }
    };

    const {getFieldDecorator} = this.props.form;
    const { dispatch } = this.props;
    const myUploadFn = (param) => {

      const serverURL = `${config}/images`
      const xhr = new XMLHttpRequest
      const fd = new FormData()

      const successFn = (response) => {
        console.log('response',response)
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        param.success({
          url: `${config}/${JSON.parse(xhr.responseText).imageUrl}`,
          meta: {
            id: 'xxx',
            title: '照片',
            alt: '照片',
            loop: true, // 指定音视频是否循环播放
            autoPlay: true, // 指定音视频是否自动播放
            controls: true, // 指定音视频是否显示控制栏
            poster: 'http://xxx/xx.png', // 指定视频播放器的封面
          }
        })
      }

      const progressFn = (event) => {
        // 上传进度发生变化时调用param.progress
        param.progress(event.loaded / event.total * 100)
      }

      const errorFn = (response) => {
        // 上传发生错误时调用param.error
        param.error({
          msg: 'unable to upload.'
        })
      }

      xhr.upload.addEventListener("progress", progressFn, false)
      xhr.addEventListener("load", successFn, false)
      xhr.addEventListener("error", errorFn, false)
      xhr.addEventListener("abort", errorFn, false)
      xhr.setRequestHeader("Authorization", `Bearer ${sessionStorage.getItem('token')}`);
      fd.append('file', param.file)
      // {Authorization: `Bearer ${sessionStorage.getItem('token')}`, 'Content-Type': 'application/json;text/plain'}
      xhr.open('POST', serverURL, true)
      xhr.send(fd)

    }
    const props = {
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [...fileList,file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    return (
      <div>
        <Form onSubmit={this.handleSubmit} style={{paddingBottom:'50px'}}>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              标题
            </span>
            )}>
            {getFieldDecorator('title', {
              rules: [{required: true, message:'标题不能为空'}],
            })(
             <Input/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              类型
            </span>
            )}>
            {getFieldDecorator('type', {
              initialValue:'普通通知',
              rules: [{required: true, message:'类型不能为空'}],
            })(
              <Select>
                <Option value={'普通通知'}>普通通知</Option>
                <Option value={'紧急通知'}>紧急通知</Option>
                <Option value={'放假通知'}>放假通知</Option>
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              内容
            </span>
            )}>
            {getFieldDecorator('content', {
              rules: [{required: true, message:'内容不能为空'}],
            })(
              <div className="editor-wrapper">
                <BraftEditor
                  value={this.state.editorState}
                  onChange={this.handleChange}
                  media={{uploadFn: myUploadFn}}
                  accepts={{
                    image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg',
                    video: false,
                    audio: false
                  }}
                />
              </div>
            )}
          </FormItem>
          <Form.Item label={'附件'} {...formItemLayoutWithLabel}>
            <div className="dropbox">
              {getFieldDecorator('file', {
              })(
                <Upload {...props} style={{width:'100%'}}>
                  <Button icon={'upload'} className={'btn-green'} block={true}>
                    点击选择
                  </Button>
                </Upload>
              )}
            </div>
          </Form.Item>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              部门
            </span>
            )}>
            {getFieldDecorator('role_id', {
              rules: [{required: true, message:'请选择公司结构'}],
            })(
              <TreeSelect onChange={this.changeRoles} treeDefaultExpandAll placeholder={'请先选择部门再选择员工'} multiple>
                {this.renderTreeNodes(this.state.all_roles)}
              </TreeSelect>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              员工
            </span>
            )}>
            {getFieldDecorator('user', {
              rules: [{required: true, message:'接收员工'}],
            })(
              <div>
                <div style={{ borderBottom: '1px solid #E9E9E9' }}>
                  {
                    this.state.all_receiver.length>0&&
                    <Checkbox
                      indeterminate={this.state.indeterminate}
                      onChange={this.onCheckAllChange}
                      checked={this.state.checkAll}
                    >
                      选择全部
                    </Checkbox>
                  }
                </div>
                <Checkbox.Group style={{ width: '100%' }}  options={this.state.all_receiver}   value={this.state.checkedList} onChange={this.onChange}>

                </Checkbox.Group>
              </div>
            )}

          </FormItem>
        </Form>
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={()=>{
            localStorage.setItem('mailHistory',this.state.editorState.toHTML())
            this.props.onClose()
          }} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={()=>{
            console.log(this.state.editorState.toHTML())
            console.log(this.props.form.getFieldsValue())
            if(!this.props.form.getFieldsValue().title){
              message.error('标题不能为空')
              return false
            }
            if(!this.props.form.getFieldsValue().type){
              message.error('类型不能为空')
              return false

            }
            if(!this.state.editorState.toHTML()){
              message.error('内容不能为空')
              return false

            }
            if(this.state.checkedList.length===0){
              message.error('请选择接收员工')
              return false

            }
            const that = this;
            let formData = new FormData();
            this.state.fileList.forEach(file => {
              formData.append('files[]', file);
            })
            formData.append("title", this.props.form.getFieldsValue().title);
            formData.append("type", this.props.form.getFieldsValue().type);
            formData.append("content", this.state.editorState.toHTML());
            formData.append("receiver", this.state.checkedList);
            for(let i=0;i<this.state.checkedList.length;i++){
              formData.append("receiver[]", this.state.checkedList[i]);
            }
            console.log(formData)
            dispatch({
              type: 'webMail/add',
              payload: formData,
              callback() {
                message.success('发送站内通知成功');
                const {
                  webMail: { searchParams },
                } = that.props;
                that.props.handleSearch(searchParams);
                that.props.onClose();
              },
            });
          }} type="primary">
            发布
          </Button>
        </div>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default (AddPoliciesFormWrap);
